import 'package:flutter/services.dart';
import 'package:flutter_common_utils/src/extends/num_extends.dart';

// 限制输入范围
class NumericRangeFormatter extends TextInputFormatter {
  final int min;
  final int max;

  NumericRangeFormatter({required this.min, required this.max});

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    // 允许清空输入
    if (newValue.text.isEmpty) return newValue;

    // 检查是否为有效数字
    final number = int.tryParse(newValue.text);
    if (number == null) return oldValue; // 非数字则拒绝

    // 检查最大值和最小值
    if (number > max) {
      final text = max.toString();
      return newValue.copyWith(text: text, selection: newValue.selection.copyWith(baseOffset: text.length, extentOffset: text.length));
    }
    if (number < min) {
      final text = min.toString();
      return newValue.copyWith(text: text, selection: newValue.selection.copyWith(baseOffset: text.length, extentOffset: text.length));
    }

    // 检查范围
    if (number < min || number > max) return oldValue; // 超出范围则拒绝

    return newValue; // 接受有效输入
  }
}

// 限制输入范围
class DecimalRangeFormatter extends TextInputFormatter {
  final double min;
  final double max;

  DecimalRangeFormatter({required this.min, required this.max});

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    // 允许清空输入
    if (newValue.text.isEmpty) return newValue;

    // 检查多个小数点
    final dotCount = newValue.text.split('.').length - 1;
    if (dotCount > 1) return oldValue;
    bool insertedZero = false;
    // 处理以小数点开头的输入（如 ".5" -> "0.5"）
    String modifiedText = newValue.text;
    if (modifiedText.startsWith('.')) {
      modifiedText = '0$modifiedText';
      insertedZero = true;
    }

    // 尝试解析为数字
    final number = double.tryParse(modifiedText);
    if (number == null) return oldValue;

    // 检查最大值和最小值
    if (number > max) {
      final text = max.toFormat45(0);
      return newValue.copyWith(text: text, selection: newValue.selection.copyWith(baseOffset: text.length, extentOffset: text.length));
    }
    if (number < min) {
      final text = min.toFormat45(0);
      return newValue.copyWith(text: text, selection: newValue.selection.copyWith(baseOffset: text.length, extentOffset: text.length));
    }
    // 检查范围
    // if (number < min || number > max) return oldValue;

    // 调整光标位置（当插入前导零时）
    TextSelection newSelection = newValue.selection;
    if (insertedZero) {
      newSelection = newSelection.copyWith(
        baseOffset: newSelection.baseOffset + 1,
        extentOffset: newSelection.extentOffset + 1,
      );
    }

    // 返回合法输入
    return TextEditingValue(
      text: modifiedText,
      selection: newSelection,
      composing: TextRange.empty,
    );
  }
}

//只能输入正小数
final TextInputFormatter digitsDoubleOnly = FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d*$'));
//只能输入小数,包括负数
final TextInputFormatter digitsDoubleAllOnly = FilteringTextInputFormatter.allow(RegExp(r'^-?\d*\.?\d*$'));
//只能输入16进制
final TextInputFormatter formatterHex = FilteringTextInputFormatter.allow(RegExp(r'[0-9a-fA-F]'));

// 自定义16进制输入格式化器
class HexInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String newText = newValue.text.toUpperCase();
    int selectionIndex = newValue.selection.end;

    // 移除非16进制字符 (0-9, A-F, x)
    String filteredText = '';
    for (int i = 0; i < newText.length; i++) {
      final char = newText[i];
      if (RegExp(r'[0-9a-fA-FxX]').hasMatch(char)) {
        filteredText += char;
      }
    }

    // 确保只有一个0x前缀
    if (filteredText.startsWith('0x') || filteredText.startsWith('0X')) {
      filteredText = '0X${filteredText.substring(2).replaceAll('0x', '').replaceAll('0X', '').replaceAll('x', '').replaceAll('X', '')}';
    } else {
      filteredText = filteredText.replaceAll('0x', '').replaceAll('0X', '').replaceAll('x', '').replaceAll('X', '');
    }

    // 光标位置调整
    final lengthDiff = filteredText.length - newText.length;
    selectionIndex = (selectionIndex + lengthDiff).clamp(0, filteredText.length);

    return TextEditingValue(
      text: filteredText,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}

// 将输入转为大写
class UpperCaseTextFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    return TextEditingValue(
      text: newValue.text.toUpperCase(),
      selection: newValue.selection,
    );
  }
}

// 将输入转为小写
class LowerCaseTextFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    return TextEditingValue(
      text: newValue.text.toLowerCase(),
      selection: newValue.selection,
    );
  }
}
